package com.makeunion.gdlbsdemo.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.text.TextUtils;
import android.util.Log;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * <p>write the description
 *
 * @author renjialiang
 * @version [版本号]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class PackageInfoUtil {

    public static String getSignString(Context context, String packageName) {
        if(TextUtils.isEmpty(packageName)) {
            Log.e("PackageInfoUtil", "The packagename is null.");
            return null;
        }
        PackageManager localPackageManager = context.getPackageManager();
        PackageInfo localPackageInfo;
        try {
            localPackageInfo = localPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            if (localPackageInfo == null) {
                Log.e("PackageInfoUtil", "PackageInfo is null.");
                return null;
            }
        } catch (PackageManager.NameNotFoundException localNameNotFoundException) {
            Log.e("PackageInfoUtil", "NameNotFoundException");
            return null;
        }
        Signature[] arrayOfSignature =  localPackageInfo.signatures;
        if ((arrayOfSignature == null) || (arrayOfSignature.length == 0)){
            Log.e("PackageInfoUtil", "The arrayOfSignature is null.");
            return null;
        }

        return MD5Util.getMessageDigest(arrayOfSignature[0].toByteArray());
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
